"""
基础异常定义模块
==============

从 shared/web/exceptions/unified_exceptions.py 提取的无依赖异常功能。
提供最基础的异常类定义，不依赖其他内部模块。
"""

import logging
from typing import Dict, Any, Optional, List
from datetime import datetime
from enum import Enum

logger = logging.getLogger(__name__)


class ErrorCode(Enum):
    """统一错误码枚举"""
    
    # 系统级错误 (1000-1999)
    SYSTEM_ERROR = 1000
    SYSTEM_MAINTENANCE = 1001
    SYSTEM_OVERLOAD = 1002
    SYSTEM_TIMEOUT = 1003
    
    # 认证相关错误 (2000-2099)
    AUTH_TOKEN_MISSING = 2000
    AUTH_TOKEN_INVALID = 2001
    AUTH_TOKEN_EXPIRED = 2002
    AUTH_CREDENTIALS_INVALID = 2003
    AUTH_USER_INACTIVE = 2004
    AUTH_USER_LOCKED = 2005
    AUTH_SESSION_EXPIRED = 2006
    
    # 权限相关错误 (2100-2199)
    PERMISSION_DENIED = 2100
    PERMISSION_INSUFFICIENT = 2101
    ROLE_REQUIRED = 2102
    ADMIN_REQUIRED = 2103
    
    # 参数验证错误 (3000-3099)
    VALIDATION_ERROR = 3000
    PARAMETER_MISSING = 3001
    PARAMETER_INVALID = 3002
    PARAMETER_TYPE_ERROR = 3003
    PARAMETER_OUT_OF_RANGE = 3004
    
    # 数据相关错误 (4000-4099)
    DATA_NOT_FOUND = 4000
    DATA_ALREADY_EXISTS = 4001
    DATA_CONFLICT = 4002
    DATA_INTEGRITY_ERROR = 4003
    DATA_FOREIGN_KEY_ERROR = 4004
    
    # 业务逻辑错误 (5000-5999)
    BUSINESS_RULE_VIOLATION = 5000
    BUSINESS_STATE_ERROR = 5001
    BUSINESS_LIMIT_EXCEEDED = 5002
    BUSINESS_OPERATION_DENIED = 5003


class ErrorSeverity(Enum):
    """错误严重程度"""
    LOW = "low"
    MEDIUM = "medium"
    HIGH = "high"
    CRITICAL = "critical"


class BaseRedFireException(Exception):
    """RedFire基础异常类"""
    
    def __init__(
        self,
        message: str,
        error_code: ErrorCode = ErrorCode.SYSTEM_ERROR,
        details: Optional[Dict[str, Any]] = None,
        severity: ErrorSeverity = ErrorSeverity.MEDIUM,
        user_message: Optional[str] = None
    ):
        self.message = message
        self.error_code = error_code
        self.details = details or {}
        self.severity = severity
        self.user_message = user_message or message
        self.timestamp = datetime.utcnow()
        
        super().__init__(self.message)
    
    def to_dict(self) -> Dict[str, Any]:
        """转换为字典格式"""
        return {
            "error_code": self.error_code.value,
            "error_type": self.__class__.__name__,
            "message": self.message,
            "user_message": self.user_message,
            "details": self.details,
            "severity": self.severity.value,
            "timestamp": self.timestamp.isoformat()
        }


class SystemException(BaseRedFireException):
    """系统异常"""
    
    def __init__(self, message: str = "System error occurred", **kwargs):
        super().__init__(
            message=message,
            error_code=ErrorCode.SYSTEM_ERROR,
            severity=ErrorSeverity.HIGH,
            **kwargs
        )


class AuthenticationException(BaseRedFireException):
    """认证异常"""
    
    def __init__(self, message: str = "Authentication failed", **kwargs):
        super().__init__(
            message=message,
            error_code=ErrorCode.AUTH_TOKEN_INVALID,
            severity=ErrorSeverity.MEDIUM,
            **kwargs
        )


class AuthorizationException(BaseRedFireException):
    """授权异常"""
    
    def __init__(self, message: str = "Permission denied", **kwargs):
        super().__init__(
            message=message,
            error_code=ErrorCode.PERMISSION_DENIED,
            severity=ErrorSeverity.MEDIUM,
            **kwargs
        )


class ValidationException(BaseRedFireException):
    """参数验证异常"""
    
    def __init__(self, message: str = "Validation failed", validation_errors: Optional[List[str]] = None, **kwargs):
        details = kwargs.get('details', {})
        if validation_errors:
            details['validation_errors'] = validation_errors
        
        super().__init__(
            message=message,
            error_code=ErrorCode.VALIDATION_ERROR,
            details=details,
            severity=ErrorSeverity.LOW,
            **kwargs
        )


class DataNotFoundException(BaseRedFireException):
    """数据未找到异常"""
    
    def __init__(self, resource: str = "Resource", resource_id: Optional[str] = None, **kwargs):
        message = f"{resource} not found"
        if resource_id:
            message += f" (ID: {resource_id})"
        
        details = kwargs.get('details', {})
        details.update({
            'resource': resource,
            'resource_id': resource_id
        })
        
        super().__init__(
            message=message,
            error_code=ErrorCode.DATA_NOT_FOUND,
            details=details,
            severity=ErrorSeverity.LOW,
            **kwargs
        )


class DataConflictException(BaseRedFireException):
    """数据冲突异常"""
    
    def __init__(self, message: str = "Data conflict occurred", **kwargs):
        super().__init__(
            message=message,
            error_code=ErrorCode.DATA_CONFLICT,
            severity=ErrorSeverity.MEDIUM,
            **kwargs
        )


class BusinessRuleException(BaseRedFireException):
    """业务规则异常"""
    
    def __init__(self, message: str = "Business rule violation", **kwargs):
        super().__init__(
            message=message,
            error_code=ErrorCode.BUSINESS_RULE_VIOLATION,
            severity=ErrorSeverity.MEDIUM,
            **kwargs
        )


class ExternalServiceException(BaseRedFireException):
    """外部服务异常"""
    
    def __init__(self, service_name: str, message: str = "External service error", **kwargs):
        details = kwargs.get('details', {})
        details['service_name'] = service_name
        
        super().__init__(
            message=f"{service_name}: {message}",
            error_code=ErrorCode.SYSTEM_ERROR,
            details=details,
            severity=ErrorSeverity.HIGH,
            **kwargs
        )


# 便捷函数
def raise_validation_error(message: str, validation_errors: Optional[List[str]] = None):
    """抛出验证错误"""
    raise ValidationException(message, validation_errors)


def raise_not_found_error(resource: str, resource_id: Optional[str] = None):
    """抛出未找到错误"""
    raise DataNotFoundException(resource, resource_id)


def raise_permission_error(message: str = "Permission denied"):
    """抛出权限错误"""
    raise AuthorizationException(message)


def raise_business_error(message: str):
    """抛出业务错误"""
    raise BusinessRuleException(message)


# 导出主要接口
__all__ = [
    "ErrorCode",
    "ErrorSeverity",
    "BaseRedFireException",
    "SystemException",
    "AuthenticationException",
    "AuthorizationException",
    "ValidationException",
    "DataNotFoundException",
    "DataConflictException",
    "BusinessRuleException",
    "ExternalServiceException",
    "raise_validation_error",
    "raise_not_found_error",
    "raise_permission_error",
    "raise_business_error"
]
